<?php

/**
 * Louder Cache
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file docs/LICENSE.txt.
 *
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@loudertechnology.com so we can send you a copy immediately.
 *
 * @category Louder
 * @package LoadBalancer
 * @subpackage Policies
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */

/**
 * Each call is dispatched to a new node, proceeding sequentially
 * through the list of nodes. The first target node is randomly
 * selected from the list.
 *
 * @category Louder
 * @package LoadBalancer
 * @subpackage Policies
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */
class RoundRobinPolicy {

	/**
	 * Obtiene el nodo segun la politica
	 *
	 * @param array $nodes
	 */
	public function getSelectedNode(array $nodes){
		$robin = MemoryRegistry::get('robin');
		if(is_bool($robin)){
			MemoryRegistry::set('robin', 0);
			$robin = 0;
		}
		$numberNodes = count($nodes);
		if($numberNodes>0){
			if($robin==$numberNodes){
				MemoryRegistry::set('robin', 0);
				$robin = 0;
			}
			$selectedNode = $nodes[$robin];
			$robin++;
			if($robin==$numberNodes){
				MemoryRegistry::set('robin', 0);
			} else {
				MemoryRegistry::set('robin', $robin);
			}
			return $selectedNode;
		} else {
			throw new LoadBalancerException("No hay nodos disponibles para balancear");
		}
	}

}